#!/usr/bin/bash

# from https://github.com/ublue-os/bazzite/blob/main/system_files/desktop/shared/usr/libexec/waydroid-container-start

if [ -z "${WAYDROID_WIDTH:-}" ] || [ -z "${WAYDROID_HEIGHT:-}" ]; then
    source /etc/default/waydroid-launcher
fi

original_user=$(ps -o user= -p $PPID)
original_home=$(getent passwd $original_user | cut -d: -f6)
for i in "${original_home}"/.config/environment.d/*.conf; do
    [[ -f "${i}" ]] && . "${i}"
done

# Ensure needed props are present
if ! grep -q "persist.waydroid.udev=true" "/var/lib/waydroid/waydroid_base.prop"; then
  sudo sh -c 'echo -e "persist.waydroid.udev=true" >> /var/lib/waydroid/waydroid_base.prop'
fi

if ! grep -q "persist.waydroid.uevent=true" "/var/lib/waydroid/waydroid_base.prop"; then
  sudo sh -c 'echo -e "persist.waydroid.uevent=true" >> /var/lib/waydroid/waydroid_base.prop'
fi

if [[ ! -z "$WAYDROID_DENSITY" ]]; then
  if ! grep -q "ro.sf.lcd_density=" "/var/lib/waydroid/waydroid_base.prop"; then
    echo "ro.sf.lcd_density=${WAYDROID_DENSITY}" | sudo tee -a /var/lib/waydroid/waydroid_base.prop
  else
    sudo sed -i "s/ro.sf.lcd_density=.*/ro.sf.lcd_density=${WAYDROID_DENSITY}/g" /var/lib/waydroid/waydroid_base.prop
  fi
fi
sudo sed -i "s/ro.hardware.gralloc=.*/ro.hardware.gralloc=${WAYDROID_GRALLOC:-minigbm_gbm_mesa}/g" /var/lib/waydroid/waydroid_base.prop

# Add controller fixes automatically
# if [[ -f "/usr/share/ublue-os/waydroid/Vendor_28de_Product_11ff.kl" ]]; then
#   mkdir -p "/var/lib/waydroid/overlay/system/usr/keylayout"
#   cp "/usr/share/ublue-os/waydroid/Vendor_28de_Product_11ff.kl" "/var/lib/waydroid/overlay/system/usr/keylayout/"
# fi

sudo systemctl start waydroid-container.service
